export default {
  data() {
    return {
      editStatus: false, // 点管理改变的状态
      n: '',
      // 购物车列表
      buyCarList: [],
      selectedList: [], // 已勾选列表
      checkedAllStatus: false, // 勾选全选
    }
  },

  computed: {
    // 商品总数
    goodsTotal() {
      let num =
        this.buyCarList.length === 0
          ? [].length
          : this.buyCarList
              .map((item) => item.shoppingTrolleyList)
              .reduce((a, b) => a.concat(b)).length
      return num
    },

    // 结算数量
    settlementAmount() {
      let sum = 0
      this.buyCarList.map((item) => {
        sum += item.shoppingTrolleyList.filter((s) => s.checked).length
      })
      return sum
    },

    // 价格合计
    priceTotal() {
      let priceSum = 0
      this.buyCarList.map((item) => {
        item.shoppingTrolleyList.map((s) => {
          if (s.checked) {
            // 保留小数点后2位
            priceSum += parseFloat(s.b_price.toFixed(2)) * s.count
          }
        })
      })
      return priceSum
    },
  },

  // 监听下拉刷新
  onPullDownRefresh() {
    this.getBuyCarList()
  },

  created() {
    this.getBuyCarList()
  },

  methods: {
    // 获取购物车列表
    async getBuyCarList() {
      let data = {
        pageIndex: 1,
        pageSize: 500,
        storeid: this.$store.state.userInfoDetail.store.storeId,
      }
      uni.showLoading()
      try {
        const res = await this.$api.buyCar.ShoppingTrolleyList(data)
        if (res.data.list) {
          // 添加个checked选中字段
          res.data.list.forEach((item) => {
            item.checked = false
            item.shoppingTrolleyList.forEach((s) => {
              s.checked = false
            })
          })
          this.buyCarList = res.data.list
        } else {
          this.buyCarList = []
        }
        console.log('购物车列表', this.buyCarList)
      } catch (err) {}
      uni.hideLoading()
      uni.stopPullDownRefresh()
    },

    // 点击商品跳转到详情页预览商品
    goGoodsDetailPage(data) {
      uni.navigateTo({
        url:
          '/pages_carGoods/carGoodsDetail/carGoodsDetail?id=' +
          data.car_supplies_id,
      })
    },

    // 购物车为空时，点击去逛逛
    goHomePage() {
      uni.switchTab({
        url: `/pages/index/index`,
      })
    },

    // 商品计数
    goodsCountChange(e) {
      this.updateBuyCarGoods(false, e)
    },

    // 勾选店铺, 会把此店铺的所有商品勾选上
    checkedStore(item) {
      item.checked = !item.checked
      item.shoppingTrolleyList.forEach((s) => {
        s.checked = item.checked
      })

      // 自动处理是否需要勾选全选
      this.handlerAutoCheckedAll()
    },

    // 勾选单个商品
    checkedGoods(item, storeItem) {
      item.checked = !item.checked
      // 判断此店铺下的商品是否全部勾选，如果checked含有false，则取消店铺勾选，将店铺的checked改为false，
      let flag = storeItem.shoppingTrolleyList
        .map((s) => s.checked)
        .includes(false)
      storeItem.checked = !flag

      // 自动处理是否需要勾选全选
      this.handlerAutoCheckedAll()
    },

    // 自动处理是否需要勾选全选
    handlerAutoCheckedAll() {
      // 只要有一个店铺的勾选checked值为false，则取消全选，将全选的checkedAllStatus改为false
      let flagAll = this.buyCarList.map((b) => b.checked).includes(false)
      this.checkedAllStatus = !flagAll
    },

    // 点击全选
    checkedAll() {
      this.checkedAllStatus = !this.checkedAllStatus
      // 遍历购物车列表，将每一项勾选改为全选的状态
      this.buyCarList.forEach((b) => {
        b.checked = this.checkedAllStatus
        b.shoppingTrolleyList.forEach((sl) => {
          sl.checked = this.checkedAllStatus
        })
      })
    },

    // 处理出已选列表，店铺id和商品id，结构购物车提交订单接口的入参结构
    handlerSelectedList() {
      let arr = []
      this.buyCarList.map((item) => {
        if (item.checked) {
          arr.push({
            buy_car_id: item.shoppingTrolleyList.map(
              (sl) => sl.shopping_trolley_id
            ),
            store_id: item.store_id,
          })
        } else {
          let hasChecked = item.shoppingTrolleyList
            .map((sl) => sl.checked)
            .includes(true)
          if (hasChecked) {
            arr.push({
              buy_car_id: item.shoppingTrolleyList
                .filter((sl) => sl.checked)
                .map((c) => c.shopping_trolley_id),
              store_id: item.store_id,
            })
          }
        }
      })
      this.selectedList = arr
      console.log('已选列表', this.selectedList)
    },

    // 请求编辑修改数量 或 删除购物车商品
    async updateBuyCarGoods(isdeleted, editData = {}) {
      let arr = []
      // true为删除购物车商品，false为修改商品数量
      if (isdeleted) {
        // 处理组装请求参数
        this.buyCarList.map((item) => {
          item.shoppingTrolleyList.map((s) => {
            if (s.checked) {
              arr.push({
                id: s.shopping_trolley_id,
                count: s.count,
                isdeleted,
              })
            }
          })
        })
      } else {
        arr.push({
          id: editData.index,
          count: editData.value,
          isdeleted,
        })
      }
      console.log(arr)

      uni.showLoading()
      try {
        const res = await this.$api.buyCar.UpdateShoppingTrolley({
          list: arr,
        })
        console.log(res)
        isdeleted ? this.getBuyCarList() : false
      } catch (err) {}
      uni.hideLoading()
    },

    // 结算 or 删除
    // 通过editStatus判断，true表示删除，false表示结算
    submit() {
      // 如果结算商品为0，提示
      if (this.settlementAmount === 0) {
        uni.showToast({ title: '您还没有选择商品哦', icon: 'none' })
        return false
      }

      if (this.editStatus) {
        uni.showModal({
          content: '确认将商品删除？',
          cancelText: '我再想想',
          confirmColor: '#FBB000',
          success: (res) => {
            if (res.confirm) {
              this.updateBuyCarGoods(true)
            }
          },
        })
      } else {
        this.handlerSelectedList()
        let params = JSON.stringify(this.selectedList)
        uni.navigateTo({
          url: `/pages_order/carGoodsOrder/submitOrder/submitOrder?data=${params}&tag=buyCar`,
        })
      }
    },
  },
}
